package mapper;

import classloader.MyClassLoader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;
import server.Request;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class MappedWrapper {
    private HashMap<String, HttpServlet> servletMap = new HashMap<>(); 						//   "/lagou"	--> HttpServlet对象

    public MappedWrapper(String webXmlDirPath)  {
        // InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(webXmlPath);


        try {
            InputStream resourceAsStream = new FileInputStream(webXmlDirPath + "/web.xml");
            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                MyClassLoader myClassLoader = new MyClassLoader(webXmlDirPath);
                Class aClass = myClassLoader.findClass(servletClass);
                servletMap.put(urlPattern, (HttpServlet) aClass.newInstance());

            }



        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public HttpServlet findFirstServlet(String urlPath) {
        return servletMap.get(urlPath);
    }


}
